package com.lys.oss.service.imp;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lys.oss.service.OssService;
import com.lys.oss.utils.ConstantPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Service
public class OssServiceImp implements OssService {

    public String uploadFileAvatar(MultipartFile file) {

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtils.END_POIND;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;


        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取文件名称和输入流
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            //根据uuid修改文件名
            String uid = UUID.randomUUID().toString().replaceAll("-", "");
            //获取当前时间
            String date = new DateTime().toString("yyyy/MM/dd");
            String fileName = date+"/"+uid+originalFilename;

            ossClient.putObject(bucketName, fileName, inputStream);

            ossClient.shutdown();

            // https://edu-lys.oss-cn-hangzhou.aliyuncs.com/QQ%E5%9B%BE%E7%89%8720220612113528.jpg
            String url ="https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
